<?php

namespace haibao\jiepai\data;


class Message extends \haibao\jiepai\data\BaseMysql
{

    public function __construct()
    {
        parent::__construct('\haibao\jiepai\model\data\messages\CmsMessagesManage');
    }

    public function getPushList($options)
    {
        $pushList = array('list' => array(), 'cnt' => 0);
        $select = 'select m.*,a.`Name`  ';
        $count = 'select count(*) as count ';
        $sql = 'from cms_messages_push m left join cms_admin a on m.AdminID=a.AdminID where 1=1';

        $date = date('Y-m-d H:i:s');

        switch ($options['pushStatus']) {
            case 0:
                $sql .= ' and m.Flag=0';
                break;
            case 1:
                $sql .= ' and m.Flag=0 and m.PublishTime>"' . $date . '"';
                break;
        }

        if (isset($options['keyword']) && $options['keyword']) {
            $sql .= ' and  m.Message like "%' . $options['keyword'] . '%"';
        }

        if (isset($options['targetView']) && $options['targetView']) {
            $sql .= ' and m.TargetView=' . $options['targetView'];
        }

        if (isset($options['editor']) && $options['editor']) {
            $sql .= ' and m.AdminID=' . $options['editor'];
        }

        //时间
        if (isset($options['start']) && $options['start'] && isset($options['end']) && $options['end']) {
            $sql .= ' and m.PublishTime between "' . $options['start'] . '" and "' . $options['end'] . '"';
        }

        $result = $this->query($select . $sql . ' ORDER BY PublishTime DESC limit ' . ($options['page'] - 1) * $options['pageSize'] . ',' . $options['pageSize']);

        while ($row = $result->fetch_assoc()) {
            array_push($pushList['list'], $row);
        }
        if ($options['page'] == 1) {
            $arr = $this->query($count . $sql)->fetch_assoc();
            $pushList['cnt'] = $arr['count'];
        }
        return $pushList;
    }


    public function getNoticeList($options)
    {
        $noticeList = array('list' => array(), 'cnt' => 0);
        $select = 'select m.*,a.`Name`  ';
        $count = 'select count(*) as count ';
        $sql = 'from cms_messages_manage m left join cms_admin a on m.AdminID=a.AdminID where 1=1 and Category=' . \haibao\jiepai\model\data\messages\CmsMessagesManage::CATEGORY_MESSAGE;

        $date = date('Y-m-d H:i:s');

        switch ($options['type']) {
            case 'all':
                $sql .= ' and m.Flag=0';
                break;
            case 'noPublish':
                $sql .= ' and m.Flag=0 and m.PublishTime>"' . $date . '"';
                break;
        }

        if (isset($options['keyword']) && $options['keyword']) {
            $sql .= ' and  m.Summary like "%' . $options['keyword'] . '%"';
        }

        if (isset($options['noticeType']) && $options['noticeType']) {
            $sql .= ' and m.Type=' . $options['noticeType'];
        }

        //时间
        if (isset($options['start']) && $options['start'] && isset($options['end']) && $options['end']) {
            $sql .= ' and m.PublishTime between "' . $options['start'] . '" and "' . $options['end'] . '"';
        }

        $result = $this->query($select . $sql . ' ORDER BY PublishTime DESC limit ' . ($options['page'] - 1) * $options['pageSize'] . ',' . $options['pageSize']);

        while ($row = $result->fetch_assoc()) {
            array_push($noticeList['list'], $row);
        }
        if ($options['page'] == 1) {
            $arr = $this->query($count . $sql)->fetch_assoc();
            $noticeList['cnt'] = $arr['count'];
        }
        return $noticeList;
    }

    public function getNoticeInfo($noticeId)
    {

        $sql = 'select * from cms_messages_manage where ID = %s';
        return $this->query($sql, array($noticeId))->fetch_assoc();
    }

    public function getUserIdAndSaveMessage($userId, $messageId, $homeTopTitle)
    {

        $sql = 'select UserID from cms_users where Flag=0 and  UserID>%s LIMIT 1000';
        $result = $this->query($sql, array($userId));

        $userIds = array();
        while ($result->fetch_assoc()) {
            array_push($userIds, $result->getData('UserID'));
        }
        if ($userIds) {

            $sql = "insert into cms_messages (UserID,TypeID,Type) values";
            $sqlArr = $valArr = array();
            foreach ($userIds as $userId) {
                array_push($sqlArr, '(%s,%s,%s)');
                array_push($valArr, $userId);
                array_push($valArr, $messageId);
                array_push($valArr, $homeTopTitle ? 6 : 5);
            }
            $sql .= implode(',', $sqlArr);
            $this->query($sql, $valArr);

            $userId = array_pop($userIds);
            $this->getUserIdAndSaveMessage($userId, $messageId, $homeTopTitle);
        }
    }

    public function getVisitorIdAndSaveMessage($userId, $messageId, $homeTopTitle)
    {

        $sql = 'select VisitorID from cms_visitors where Flag=0 and VisitorID>%s LIMIT 1000';
        $result = $this->query($sql, array($userId));

        $userIds = array();
        while ($result->fetch_assoc()) {
            array_push($userIds, $result->getData('VisitorID'));
        }
        if ($userIds) {

            $sql = "insert into cms_messages (UserID,TypeID,Type) values";
            $sqlArr = $valArr = array();
            foreach ($userIds as $userId) {
                array_push($sqlArr, '(%s,%s,%s)');
                array_push($valArr, $userId);
                array_push($valArr, $messageId);
                array_push($valArr, $homeTopTitle ? 6 : 5);
            }
            $sql .= implode(',', $sqlArr);
            $this->query($sql, $valArr);

            $userId = array_pop($userIds);
            $this->getUserIdAndSaveMessage($userId, $messageId, $homeTopTitle);
        }
    }

    public function getHomeTopMsg($userId, $vistorId)
    {
        $sql = 'SELECT m.MessageID,m.IsRead,m1.HomeTopTitle as HomeTopMessage,m1.Title as HomeTopTitle,m1.OpenType,m1.ContentID,m1.ContentType,m1.Url FROM cms_messages m ' .
            'LEFT JOIN cms_messages_manage m1 ON m.TypeID=m1.ID WHERE  m.Type=6  AND m1.Flag=0 and m1.PublishTime<"' . date('Y-m-d H:i:s') . '" ';
        if ($userId) {
            $sql .= ' and m.UserID=' . $userId;
        } else {
            $sql .= ' and m.VisitorID=' . $vistorId;
        }
        $sql .= ' and m.IsRead=0 ORDER BY m1.PublishTime DESC LIMIT 1 ';

        return $this->query($sql)->fetch_assoc();
    }

    public function pushWelcomeMsg($userId, $visitorId)
    {
        $messageManageId = 0;
        $sql = 'SELECT ID FROM cms_messages_manage WHERE Category=3 ';
        $result = $this->query($sql);
        while ($result->fetch_assoc()) {
            $messageManageId = $result->getData('ID');
        }
        $sqlMessage = "insert into cms_messages (UserID,VisitorID,FromUserID,TypeID,Type,IsRead,CreateTime,Flag)
    			values (%s,%s,null,%s,5,0,%s,0)";
        $this->query($sqlMessage, array($userId, $visitorId, $messageManageId, date('Y-m-d H:i:s')));
    }

    public function countManageMessage($userId, $vistorId)
    {
        $now = date('Y-m-d H:i:s');
        $list = array();
        $sql = 'SELECT count(*) as count FROM cms_messages m  ' .
            'LEFT JOIN cms_messages_manage m1 ON m.TypeID=m1.ID WHERE  m.IsRead=0 and m.Type=5  AND m1.Flag=0 and m1.PublishTime<"' . $now . '" ';
        if ($userId) {
            $sql .= ' and m.UserID=' . $userId;
        } else {
            $sql .= ' and m.VisitorID=' . $vistorId;
        }
        $result = $this->query($sql);
        while ($result->fetch_assoc()) {
            $list = $result->getData('count');
        }
        return $list;
    }

    public function countCommentMessage($userId)
    {
        $list = array();
        $sql = 'select count(*) as count from cms_messages where Type IN(1,2,7,8) AND UserID=%s AND IsRead=0 ';
        $result = $this->query($sql, array($userId));
        while ($result->fetch_assoc()) {
            $list = $result->getData('count');
        }
        return $list;
    }

    public function countPraiseMessage($userId, $isOld)
    {
        $list = array();
        $sql = 'SELECT count(*) as count FROM cms_messages_praise WHERE MessageID IS NULL AND ToUserID=%s';
        if ($isOld) $sql .= ' and Type!=6';
        $result = $this->query($sql, array($userId));
        while ($result->fetch_assoc()) {
            $list = $result->getData('count');
        }
        return $list;
    }

    public function countPraiseMessagePicture($userId)
    {
        $list = array();
        $sql = 'SELECT count(*) as count FROM cms_messages_praise WHERE MessageID IS NULL AND ToUserID=%s AND Type IN (7,8,9)';
        $result = $this->query($sql, array($userId));
        while ($result->fetch_assoc()) {
            $list = $result->getData('count');
        }
        return $list;
    }

    public function countAdviceMessage($userId)
    {
        $list = array();
        $sql = 'SELECT count(*) as count FROM cms_advice_reply r  LEFT JOIN cms_advice a ON r.AdviceID=a.AdviceID WHERE a.UserID=%s AND r.`Status`=0';

        $result = $this->query($sql, array($userId));
        while ($result->fetch_assoc()) {
            $list = $result->getData('count');
        }
        return $list;
    }

    public function getUserIgnore($userId)
    {
        $sql = 'SELECT u.UserID,u.NickName,u.AvatarID FROM cms_messages_ignore i LEFT JOIN cms_users u ON i.IgnoreID=u.UserID where i.UserID=%s order by i.CreateTime desc';
        return $this->normalQuery($sql, array($userId));
    }

    public function setUserIgnore($userId, $ignoreId, $type)
    {

        $sql = ($type == 1)
            ? 'insert into cms_messages_ignore set UserID=%s,IgnoreID=%s;'
            : 'DELETE FROM cms_messages_ignore WHERE UserID=%s AND IgnoreID=%s;';

        $result = $this->query($sql, array($userId, $ignoreId));
        if ($result) {
            if ($type == 1) {
                $deleteSql = 'UPDATE cms_messages SET Flag=-1 WHERE UserID=%s AND FromUserID=%s';
                $result = $this->query($deleteSql, array($userId, $ignoreId));
            }
        }
        return true;

    }

    public function getHistoryManageMessages($userId, $visitorId, $cursor)
    {

        $nowTime = date('Y-m-d H:i:s');
        $sql = 'SELECT m.MessageID,m.CreateTime as MsgCreateTime,m1.Category,m1.PublishTime as CreateTime,m1.Title,m1.Summary,m1.OpenType,m1.ContentID,m1.ContentType,m1.Url FROM cms_messages m  ' .
            'LEFT JOIN cms_messages_manage m1 ON m.TypeID=m1.ID WHERE  m.IsRead=1 and m.Type=5  AND m1.Flag=0 and m1.PublishTime<"' . $nowTime . '" ';

        if ($userId) {
            $sql .= ' and m.UserID=' . $userId;
        } else {
            $sql .= ' and m.VisitorID=' . $visitorId;
        }

        if ($cursor) $sql .= ' and m1.PublishTime < "' . date('Y-m-d H:i:s', $cursor) . '"';

        $sql .= ' ORDER BY m1.PublishTime DESC LIMIT ' . (\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LIST_PAGE_SIZE) + 1);

        return $this->normalQuery($sql);
    }

    public function getUnReadManageMessages($userId, $visitorId, $cursor, $stopCursor)
    {

        $nowTime = date('Y-m-d H:i:s');
        $sql = 'SELECT m.MessageID,m.CreateTime as MsgCreateTime,m1.Category,m1.PublishTime as CreateTime,m1.Title,m1.Summary,m1.OpenType,m1.ContentID,m1.ContentType,m1.Url FROM cms_messages m ' .
            'LEFT JOIN cms_messages_manage m1 ON m.TypeID=m1.ID WHERE m.Type=5 AND m1.Flag=0 and m1.PublishTime<"' . $nowTime . '" ';
        if (!$cursor && !$stopCursor) $sql .= ' and m.IsRead=0 ';

        if ($userId) {
            $sql .= ' and m.UserID=' . $userId;
        } else {
            $sql .= ' and m.VisitorID=' . $visitorId;
        }

        if ($cursor) $sql .= ' and m1.PublishTime < "' . date('Y-m-d H:i:s', $cursor) . '"';
        if ($stopCursor) $sql .= ' and m1.PublishTime > "' . date('Y-m-d H:i:s', $stopCursor) . '" ';

        $sql .= ' ORDER BY m1.PublishTime DESC LIMIT ' . (\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LIST_PAGE_SIZE) + 1);

        $list = $this->normalQuery($sql);
        if ($list) {
            $sql = 'update cms_messages set IsRead=1 where Type=5 ';
            if ($userId) {
                $sql .= ' and UserID=' . $userId;
            } else {
                $sql .= ' and VisitorID=' . $visitorId;
            }
            $this->query($sql);
        }
        return $list;
    }

    public function getPushMessage()
    {
        $sql = "SELECT TargetView as type,ArticleID,ArticleType,Message,PublishTime as PushTime from cms_messages_push WHERE PublishTime = %s AND Flag=0 AND IsOnlyUser=0 AND Type=2 ORDER BY PublishTime desc LIMIT 1;";
        return $this->query($sql, array(date('Y-m-d 21:00:00')))->fetch_assoc();
    }

    public function readHomeTopMsg($userId, $visitorId)
    {
        $sql = 'update cms_messages set IsRead=1 where  Type=6 ';
        if ($userId) {
            $sql .= ' and UserID=' . $userId;
        } else {
            $sql .= ' and UserID=' . $visitorId;
        }
        return $this->query($sql);
    }

    public function getHistoryCommentMessages($userId, $version, $cursor)
    {

        $nowTime = date('Y-m-d H:i:s');
        if (version_compare($version, \haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LAST_SUPPORT_VERSION_450)) >= 0) {
            $sql = 'SELECT MessageID,`Type`,TypeID,CreateTime,FromUserID FROM cms_messages WHERE Type IN(1,2,7,8) AND IsRead=1 AND UserID=%s AND Flag=0 ';
        } else {
            $sql = 'SELECT MessageID,`Type`,TypeID,CreateTime,FromUserID FROM cms_messages WHERE Type IN(1,2) AND IsRead=1 AND UserID=%s AND Flag=0 ';
        }
        if ($cursor) $sql .= ' and CreateTime < "' . date('Y-m-d H:i:s', $cursor) . '"';
        $sql .= ' ORDER BY CreateTime DESC LIMIT ' . (\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LIST_PAGE_SIZE) + 1);
        return $this->normalQuery($sql, array($userId));
    }

    public function getUnReadCommentMessages($userId, $version, $cursor, $stopCursor)
    {
        if (version_compare($version, \haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LAST_SUPPORT_VERSION_450)) >= 0) {
            $sql = 'SELECT MessageID,Type,TypeID,CreateTime,FromUserID FROM cms_messages WHERE Type IN(1,2,7,8) AND UserID=%s AND Flag=0 ';
        } else {
            $sql = 'SELECT MessageID,Type,TypeID,CreateTime,FromUserID FROM cms_messages WHERE Type IN(1,2) AND UserID=%s AND Flag=0 ';
        }
        if (!$cursor && !$stopCursor) $sql .= ' and IsRead=0 ';

        if ($cursor) $sql .= ' and CreateTime < "' . date('Y-m-d H:i:s', $cursor) . '"';
        if ($stopCursor) $sql .= ' and CreateTime > "' . date('Y-m-d H:i:s', $stopCursor) . '"';
        $sql .= ' ORDER BY CreateTime DESC LIMIT ' . (\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LIST_PAGE_SIZE) + 1);


        $list = $this->normalQuery($sql, array($userId));
        if ($list) {
            $sql = 'update cms_messages set IsRead=1 where Type in (1,2,7,8) AND UserID=%s AND Flag=0';
            $this->query($sql, array($userId));
        }
        return $list;
    }

    public function getDetailByTypeIDAndType($typeId, $type)
    {
        $sql = '';
        $isPictrue = false;
        switch ($type) {
            case 1:
                $isPictrue = true;
                $sql = 'SELECT c.CommentID,c.Content,c.SensitiveWords,a1.ArticleID,a1.Type as ArticleType,a.ContentInfo,u.NickName,u.UserID ' .
                    'FROM cms_comment c ' .
                    'LEFT JOIN cms_users u ON c.UserID=u.UserID ' .
                    'LEFT JOIN cms_article_content a ON c.TypeID=a.ArticleID AND a.Type=0 ' .
                    'LEFT JOIN cms_articles a1 ON c.TypeID=a1.ArticleID WHERE c.CommentID=%s';
                break;
            case 2:
                $isPictrue = true;
                $sql = 'SELECT r.CommentID,r.Content,r.SensitiveWords,a.ArticleID,a.Type as ArticleType,a1.ContentInfo,u.NickName,u.UserID ' .
                    'FROM cms_comment_reply r ' .
                    'LEFT JOIN cms_comment c ON r.CommentID=c.CommentID  LEFT JOIN cms_articles a ON c.TypeID=a.ArticleID ' .
                    'LEFT JOIN cms_article_content a1 ON c.TypeID=a1.ArticleID AND a1.Type=0 ' .
                    'LEFT JOIN cms_users u ON r.UserID=u.UserID ' .
                    'WHERE r.ReplyID=%s';
                break;
            case 3:
                $isPictrue = true;
                $sql = 'SELECT a1.Type as ArticleType,a1.ArticleID,a.ContentInfo FROM cms_article_content a LEFT JOIN cms_articles a1 on a.ArticleID=a1.ArticleID WHERE a.Type=0 AND a.ArticleID=%s';
                break;
            case 4:
                $sql = 'SELECT cc.TypeID as ArticleID,cc.CommentID,cc.Content,ca.Type as ArticleType FROM cms_comment cc LEFT JOIN cms_articles ca on cc.TypeID=ca.ArticleID WHERE cc.CommentID=%s';
                break;
            case 9:
                $isPictrue = true;
                $sql = 'SELECT cc.TypeID as ContentInfo FROM cms_messages_praise cc where cc.TypeID=%s limit 1';
                break;
            case 6:
                $sql = 'SELECT c.TypeID as ArticleID,r.CommentID,r.Content,ca.Type as ArticleType FROM cms_comment_reply r LEFT JOIN cms_comment c ON r.CommentID=c.CommentID ' .
                    ' LEFT JOIN cms_articles ca ON c.TypeID=ca.ArticleID WHERE ReplyID=%s';
                break;
            case 7:
                $isPictrue = true;
                $sql = 'SELECT c.CommentID,c.Content,c.SensitiveWords,u.NickName,u.UserID,c.TypeID as ContentInfo ' .
                    'FROM cms_comment c ' .
                    'LEFT JOIN cms_users u ON c.UserID=u.UserID WHERE c.CommentID=%s';
                break;
            case 8:
                $isPictrue = true;
                $sql = 'SELECT r.CommentID,r.Content,r.SensitiveWords,c.TypeID as ContentInfo,u.NickName,u.UserID ' .
                    'FROM cms_comment_reply r ' .
                    'LEFT JOIN cms_comment c ON r.CommentID=c.CommentID  ' .
                    'LEFT JOIN cms_users u ON r.UserID=u.UserID ' .
                    'WHERE r.ReplyID=%s';
                break;

        }
        $list = array();
        if ($sql) {

            $list = $this->normalQuery($sql, array($typeId));
            if ($isPictrue) {
                $list = self::mergeDataAndImage($list);
            }
        }
        if ($list) {
            return $list[0];
        }
        return $list;
    }

    public function getHistoryPraiseMessages($userId, $version, $cursor = null)
    {
        $sql = 'SELECT MessageID,TypeID,Type,CreateTime FROM cms_messages WHERE UserID=%s AND IsRead=1 AND MessageID!=-1 ';
        if (version_compare($version, \haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LAST_SUPPORT_VERSION_450)) >= 0) {
            $sql .= ' and Type IN(3,4,9,6,7,8) ';
        } else {
            $sql .= ' and Type IN(3,4,6) ';
        }
        if ($cursor) $sql .= 'AND CreateTime < "' . date('Y-m-d H:i:s', $cursor) . '"';
        $sql .= ' ORDER BY MessageID DESC LIMIT ' . (\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LIST_PAGE_SIZE) + 1);
        return $this->normalQuery($sql, array($userId));
    }

    public function getUnReadPraiseMessages($userId, $version)
    {

        if (version_compare($version, \haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LAST_SUPPORT_VERSION_450)) >= 0) {
            $sql = 'SELECT m.*,u.AvatarID,u.UserID FROM cms_messages_praise m LEFT JOIN cms_users u ON m.FromUserID=u.UserID ' .
                'WHERE m.ToUserID=%s AND m.MessageID is NULL ';
        } else {
            $sql = 'SELECT m.*,u.AvatarID,u.UserID FROM cms_messages_praise m LEFT JOIN cms_users u ON m.FromUserID=u.UserID ' .
                'WHERE m.ToUserID=%s AND m.MessageID is NULL AND TypeID!=9';
        }


        return $this->normalQuery($sql, array($userId));
    }

    public function getPraiseMessageUsers($messageId)
    {

        $sql = 'SELECT u.UserID,u.AvatarID,m.CreateTime FROM cms_messages_praise m ' .
            'LEFT JOIN cms_users u ON m.FromUserID=u.UserID ' .
            'where m.MessageID=%s ORDER BY CreateTime ASC limit 10';
        return $this->normalQuery($sql, array($messageId));
    }

    public function insertPraiseMessage($userId, $key, $message)
    {
        list($type, $typeId) = explode('_', $key);
        $insertSql = 'insert into cms_messages (UserID, TypeID, `Type`, IsRead) values (%s,%s,%s,%s)';
        $this->query($insertSql, array($userId, $typeId, $type, 1));
        $messageId = $this->getDb()->insert_id;

        $ids = array_map("array_shift", $message);

        $updateSql = 'UPDATE cms_messages_praise SET MessageID=%s WHERE ID IN(' . implode(',', $ids) . ')';
        $this->query($updateSql, array($messageId));
        return $messageId;
    }

    public function getPraiseMessageUsersByCursor($messageId, $cursor)
    {
        $sql = 'SELECT u.UserID,u.NickName,u.UserID,m.CreateTime FROM cms_messages_praise m ' .
            'LEFT JOIN cms_users u ON m.FromUserID=u.UserID ' .
            'where m.MessageID=%s ';

        if ($cursor) $sql .= ' and m.CreateTime > "' . date('Y-m-d H:i:s') . '" ';
        $sql .= ' ORDER BY CreateTime ASC LIMIT ' . (\haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LIST_PAGE_SIZE) + 1);

        return $this->normalQuery($sql, array($messageId));
    }

    /**
     * 首次进入消息
     */
    public function firstEntryMessage($userId)
    {
        $this->query('INSERT INTO cms_messages (TypeID,UserID,Type) VALUES (%s,%s,%s)', array(
            143, $userId, 5
        ));
    }

}
